<script>
import { mapGetters } from 'vuex'
import { axios } from '@/utils/request'

export default {
  name: 'qiye',
  props: {
    // 基本类型检查 (`null` 和 `undefined` 会通过任何类型验证)
    user: {
      type: Object,
    },
    canFix: {
      type: Boolean,
    },
  },

  data() {
    return {
      user_type: [],
      form: {
        subjectType: 1, // 默认为法人
        isIntegration: '',
        legalCode: '',
        legalName: '',
        legalNameJc: '',
        bidderCodeType: [],
        idCard: '', // 身份证号
        idCardScan: '', // 身份证扫描件（可以是文件对象）
        responsiblePerson: '', // 机构负责人
        address: '', // 住址
      },
      rules: {
        subjectType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
        isIntegration: [{ required: true, message: '请选择是否三证合一', trigger: 'change' }],
        legalCode: [{ required: true, message: '请输入统一社会信用代码号或身份证号' }],
        legalName: [{ required: true, message: '请输入供应商/投标人/受让方全称' }],
        legalNameJc: [{ required: true, message: '请输入供应商/投标人/受让方简称' }],
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  watch: {
    'form.subjectType'(newVal) {
      // 通知父组件 subjectType 变化
      this.$emit('region-changed', newVal)
      if (newVal == '2') {
        // 自然人
        this.form.legalCode = '' // 清空之前的值
        this.updateRulesForNaturalPerson()
      } else {
        this.form.idCard = ''
        this.form.idCardScan = null
        this.form.responsiblePerson = ''
        this.form.address = ''
        this.updateRulesForLegalEntity()
      }
    },
    user: {
      handler: function(newVal, oldVal) {
        this.updateFormValues(newVal)
      },
    },
  },
  methods: {
    getInfo(v) {
      return axios.post('/register/subjectLegal/queryByInfo', { sysUserId: v.sysUserId }).then(r => {
        return r.result
      })
    },
    updateFormValues(r) {
      this.getInfo(r).then(newValues => {
        // 使用 Vue.set 或 this.$set 来更新 form 对象的属性
        Object.keys(this.form).forEach(key => {
          if (key === 'bidderCodeType') {
            newValues[key] = newValues[key]?.split(',')
          }
          this.$set(this.form, key, newValues[key])
        })
      })
    },
    updateRulesForLegalEntity() {
      this.rules = {
        subjectType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
        isIntegration: [{ required: true, message: '请选择是否三证合一', trigger: 'change' }],
        legalCode: [{ required: true, message: '请输入统一社会信用代码号' }],
        legalName: [{ required: true, message: '请输入供应商/投标人/受让方全称' }],
        legalNameJc: [{ required: true, message: '请输入供应商/投标人/受让方简称' }],
        idCard: [], // 不需要验证身份证号
      }
    },
    updateRulesForNaturalPerson() {
      this.rules = {
        subjectType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
        isIntegration: [], // 不需要验证是否三证合一
        legalCode: [], // 不需要验证统一社会信用代码号
        legalName: [], // 不需要验证供应商/投标人/受让方全称
        legalNameJc: [], // 不需要验证供应商/投标人/受让方简称
        idCard: [{ required: true, message: '请输入身份证号' }],
      }
    },
    handleChange(info) {
      if (info.file.status == 'done') {
        this.form.idCardScan = info.file.response // 假设服务器返回了文件信息
        this.$message.success(`${info.file.name} 上传成功`)
      } else if (info.file.status == 'error') {
        this.$message.error(`${info.file.name} 上传失败`)
      }
    },
    getUserType() {
      this.$http.get('/register/common/getDictItems/legal_user_type').then(r => {
        this.user_type = r.result
      })
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            resolve(this.form) // 验证通过，返回表单值
          } else {
            reject('表单验证失败') // 验证失败，返回错误信息
          }
        })
      })
    },
  },
  created() {
    // 初始化规则
    this.updateRulesForLegalEntity()
    this.getUserType()
    if (this.user) {
      this.updateFormValues(this.user)
    }
  },
}
</script>

<template>
  <a-form-model ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-form-model-item label="机构类型" prop="subjectType">
      <a-select :disabled="!canFix" v-model="form.subjectType" placeholder="请选择机构类型">
        <a-select-option :value="1">法人</a-select-option>
        <a-select-option :value="2">自然人</a-select-option>
      </a-select>
    </a-form-model-item>

    <!-- 法人相关表单项 -->
    <a-form-model-item label="是否三证合一" prop="isIntegration" v-if="form.subjectType == '1'">
      <a-radio-group :disabled="!canFix" v-model="form.isIntegration">
        <a-radio :value="0">否</a-radio>
        <a-radio :value="1">是</a-radio>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item label="统一社会信用代码号" prop="legalCode" v-if="form.subjectType == '1'">
      <a-input :disabled="!canFix" v-model="form.legalCode" />
      <div class="tip">
        温馨提示：统一社会信用代码(注册号)(格式设计为18位)将作为会员登录号，请确认无误后填写，格式有误将审核不予通过。
      </div>
    </a-form-model-item>
    <a-form-model-item label="供应商/投标人/受让方 全称" prop="legalName" v-if="form.subjectType == '1'">
      <a-input :disabled="!canFix" v-model="form.legalName" />
    </a-form-model-item>
    <a-form-model-item label="供应商/投标人/受让方 简称" prop="legalNameJc" v-if="form.subjectType == '1'">
      <a-input :disabled="!canFix" v-model="form.legalNameJc" />
    </a-form-model-item>
    <!-- 自然人相关表单项 -->
    <a-form-model-item label="身份证号" prop="idCard" v-if="form.subjectType == '2'">
      <a-input :disabled="!canFix" v-model="form.idCard" />
      <div class="tip">
        温馨提示：请输入有效的身份证号码。
      </div>
    </a-form-model-item>
    <a-form-model-item label="身份证扫描件" v-if="form.subjectType == '2'">
      <j-upload :disabled="!canFix" v-model="form.idCardScan"></j-upload>
    </a-form-model-item>
    <a-form-model-item label="机构负责人" v-if="form.subjectType == '2'">
      <a-input :disabled="!canFix" v-model="form.responsiblePerson" />
    </a-form-model-item>
    <a-form-model-item label="住址" v-if="form.subjectType == '2'">
      <a-input :disabled="!canFix" v-model="form.address" />
    </a-form-model-item>
    <a-form-model-item label="用户类型" prop="bidderCodeType">
      <a-checkbox-group :disabled="!canFix" v-model="form.bidderCodeType">
        <a-checkbox v-for="type in user_type" :key="type.value" :value="type.value" name="type">{{
          type.label
        }}</a-checkbox>
      </a-checkbox-group>
    </a-form-model-item>
  </a-form-model>
</template>

<style scoped>
.tip {
  color: #999;
  font-size: 0.8em;
}
</style>

<style scoped lang="less">
/deep/ .ant-checkbox-wrapper {
  margin-left: 8px;
  width: 100px;
}
</style>
